#include "msp.h"


extern uint8_t MSP_Buf[];

MSP_DataTypeDef MSP_DataStructure;
static ErrorStatus MSP_crc8_dvb_s2(uint32_t frameLen);


/**
 * @brief   MSP协议解码
 * @param   frameLen: 帧长
 * @param   nextFrameHead: 由于Buf一般是传输数据长度的两倍以上，所以会检测到下一个帧头
 **/
void MSP_Decode(uint32_t frameLen)
{

    if(MSP_crc8_dvb_s2(frameLen)==SUCCESS)
    {
        MSP_DataTypeDef MSP_DataStructure;

        //解码协议版本号
        if(MSP_Buf[1]=='M')
            MSP_DataStructure.MSP_Version=1;
        else if(MSP_Buf[1]=='X')
            MSP_DataStructure.MSP_Version=2;

        //解码数据帧类型
        if(MSP_Buf[2]=='<')
            MSP_DataStructure.MSP_MsgType=MSP_MsgType_Request;
        else if(MSP_Buf[2]=='>')
            MSP_DataStructure.MSP_MsgType=MSP_MsgType_Response;
        else if(MSP_Buf[2]=='!')
            MSP_DataStructure.MSP_MsgType=MSP_MsgType_Error;

        //解码数据帧功能
        MSP_DataStructure.MSP_Fun=((uint16_t)MSP_Buf[5]<<8)|MSP_Buf[4];
        L0X3901_AllDataRead(MSP_DataStructure.MSP_Fun);
    }
}

/* Private functions ---------------------------------------------------------*/


/**
 * @brief   MSP协议校验
 * @param   MSP_Buf: MSP协议存储区域
 * @param   frameLen: 帧长度
 **/
static ErrorStatus MSP_crc8_dvb_s2(uint32_t frameLen)
{
    uint8_t crc=0;
    uint16_t crcSize=frameLen-4;
    for(uint32_t i=0;i<crcSize;++i)
    {
        crc ^= MSP_Buf[i+3];
        for (int ii = 0; ii < 8; ++ii)
        {
            if (crc & 0x80)
                crc = (crc << 1) ^ 0xD5;
            else
                crc = crc << 1;
        }
    }

    if(crc==MSP_Buf[frameLen-1])
        return SUCCESS;
    else
        return ERROR;
}


